package com.example.demo.util;

/**
 * @author moguai
 * @version 1.0
 * @date 2022/3/19 14:38
 */

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author CL
 */
@Component
public class RedisUtil {

    public static Long EXPIRE;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${TOKEN.EXPIRE}")
    public void setExpire(Long EXPIRE) {
        RedisUtil.EXPIRE = EXPIRE;
    }

    private static RedisUtil redisUtils;

    /**
     * 初始化
     */
    @PostConstruct
    public void init() {
        redisUtils = this;
        redisUtils.redisTemplate = this.redisTemplate;
    }

    public static void setWhite(String key, Integer id) {
        redisUtils.redisTemplate.opsForValue().set("whiteList:" + key, String.valueOf(id));
        redisUtils.redisTemplate.expire("whiteList:" + key, EXPIRE, TimeUnit.MILLISECONDS);
    }

    /**
     * 删出key
     *
     * @param key
     */
    public static void deleteWhite(String key) {
        redisUtils.redisTemplate.opsForValue().getOperations().delete("whiteList:" + key);
    }

    public static boolean keyIsExists(String key) {
        if (key != null || StringUtils.isNotEmpty(key)) {
            return redisUtils.redisTemplate.hasKey("whiteList:" + key);
        }
        return false;
    }

    public String getValue(String key) {
        return redisUtils.redisTemplate.opsForValue().get("whiteList:" + key);
    }

    public static void hset(String key, String hashKey, Object object) {
        redisUtils.redisTemplate.opsForHash().put(key, hashKey, object);
    }

    public static void hdelete(String key, String hashKey) {
        redisUtils.redisTemplate.opsForHash().delete(key, hashKey);
    }


    /**
     * 删除key的所有值
     *
     * @param key
     */
    public static void deleteKey(String key) {
        redisUtils.redisTemplate.opsForHash().getOperations().delete(key);
    }

    /**
     * 判断key下是否有值
     *
     * @param key
     */
    public static Boolean hasKey(String key) {
        return redisUtils.redisTemplate.opsForHash().getOperations().hasKey(key);
    }

    /**
     * 判断key和hasKey下是否有值
     *
     * @param key
     * @param hasKey
     */
    public static Boolean hasKey(String key, String hasKey) {
        return redisUtils.redisTemplate.opsForHash().hasKey(key, hasKey);
    }

}